package analyse;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.stock.StockQuery;
import com.stock.dao.Averline;
import com.stock.dao.AverlineDAO;

import spring.SpringApplicationCtx;
import util.DateUtil;

import data.Constant;
import data.deal.SinaIndustryDaySort;
import dataconnect.ConnectionFactory;
import dataconnect.SqlUtil;

public class StockAnalyse {
	
	Connection conn = ConnectionFactory.getConnection();
	public StockAnalyse(Date date) {
		try {
			String updateStr = "update stockanlyz set amountBat=?,minPrice=?,minToDays=?,maxPice=?,maxToDays=?,ratePercent=?,fallDays=?,amtCreDays=?,updays=?,"
					+ "averAmount=?,dayPercentWave=?,priceLevel = ?,curPrice= ?," +
					"FiveDayPrice=?,TenDayPrice=?,thirtyDayPrice=?,twentyDayPrice=?,averlineUp=? where number = ?";
			String dataStr = DateUtil.format(date);
			PreparedStatement ps = conn.prepareStatement(updateStr);
			String info = "select number from stockanlyz";
			Statement stmtInfo = conn.createStatement();
			SqlUtil.update("delete from averline where dealDate = '"+dataStr+"'");
			ResultSet rsInfo = stmtInfo.executeQuery(info);
			
			List<Averline> lastAverlines = getPredayAverlines(date);
			
			StockQuery stockQuery = (StockQuery) SpringApplicationCtx.getCtx().getBean("StockQuery");
			Session session = stockQuery.getCurrentSession();
			Transaction tx = session.beginTransaction();
			
			while(rsInfo.next()){
				List<DealDayData> datas = new ArrayList<DealDayData>();
				
				String sql = "select * from stockdaydeal where number = '"+rsInfo.getString("number")+"' and amount<>0 and dealday<='"+dataStr+"' order by dealday DESC LIMIT 0,60";
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery(sql);
				int index = 0;
				while (rs.next()) {
					DealDayData ddd = new DealDayData();
					ddd.setAmount(rs.getBigDecimal("amount"));
					ddd.setDate(rs.getDate("dealday"));
					ddd.setBeginPrice(rs.getBigDecimal("beginPrice"));
					ddd.setMaxPrice(rs.getBigDecimal("maxPrice"));
					ddd.setMinPrice(rs.getBigDecimal("minPrice"));
					ddd.setPrice(rs.getBigDecimal("price"));
					ddd.setPredayPrice(rs.getBigDecimal("predayprice"));
					ddd.setRatePercent(rs.getBigDecimal("ratePercent"));
					ddd.setAmountBat(rs.getBigDecimal("amountBat"));
					ddd.setNumber(rs.getString("number"));
					index++;
					ddd.setSeq(index);
					datas.add(ddd);
				}
				rs.close();
				stmt.close();
				if(datas.isEmpty()){
					continue;
				}
				LowestPriceAlyz lpa = new LowestPriceAlyz();
				DealAmountAlyz daa = new DealAmountAlyz();
				PriceIncreAlyz prz = new PriceIncreAlyz();
				
				DealDayData ddd = daa.alanalyze(datas);
				if(ddd!=null){
					ps.setBigDecimal(1, ddd.getAmountBat());
					ps.setBigDecimal(6, ddd.getRatePercent());
					ps.setInt(8, ddd.getAmtCreDays());
				}else{
					ps.setBigDecimal(1, Constant.ZERO);
					ps.setBigDecimal(6, Constant.ZERO);
					ps.setInt(8, -1);
				}
				DealDayData ddd2 = lpa.alanalyze(datas);
				ps.setBigDecimal(2, ddd2.getMinPrice());
				ps.setInt(3, ddd2.getSeq()-1);
				DealDayData ddd3 = prz.alanalyze(datas);
				ps.setBigDecimal(4, ddd3.getPrice());
				ps.setInt(5, ddd3.getSeq()-1);
				ps.setInt(7, ddd2.getFallDays());
				ps.setInt(9, ddd3.getUpDays());
				ps.setBigDecimal(10, ddd.getAverAmount());
				ps.setBigDecimal(11, ddd3.getDayPercentWave());
				if(ddd2.getPriceLevel()==-1){
					ps.setInt(12, -1);
				}else if(ddd3.getPriceLevel()==1){
					ps.setInt(12, 1);
				}else{
					ps.setInt(12, 0);
				}
				ps.setBigDecimal(13, ddd.getPrice());
				ps.setBigDecimal(14, ddd3.getFiveDayPrice());
				ps.setBigDecimal(15, ddd3.getTenDayPrice());
				ps.setBigDecimal(16, ddd2.getThirtyDayPrice());
				ps.setBigDecimal(17, ddd2.getTwentyDayPrice());
				for (Averline averline : lastAverlines) {
					Averline averline2 = ddd2.getAverline();
					if(averline2.getNumber().equals(averline.getNumber())){
						if(averline2.getAver30().compareTo(averline.getAver30())>0){
							ps.setBoolean(18, true);
						}else if(averline2.getAver30().compareTo(averline.getAver30())==0){
							if(averline2.getAver20().compareTo(averline.getAver20())>0){
								ps.setBoolean(18, true);
							}else if(averline2.getAver20().compareTo(averline.getAver20())==0){
								ps.setBoolean(18, averline2.getAver5().compareTo(averline.getAver5())>0);
							}
						}else{
							ps.setBoolean(18, false);
						}
					}
				}
				ps.setString(19, rsInfo.getString("number"));
				ps.addBatch();
				if(DateUtil.format(ddd2.getAverline().getDealdate()).equals(dataStr)){
					session.save(ddd2.getAverline());
				}
			}
			conn.setAutoCommit(false);
			ps.executeBatch();
			conn.commit();
			conn.setAutoCommit(true);
			
			tx.commit();
			session.close();
			System.out.println("industy head......");
			new SinaIndustryDaySort(date);
			System.out.println("industy head complete!");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private List<Averline> getPredayAverlines(Date date){
		AverlineDAO averlineDAO = (AverlineDAO)SpringApplicationCtx.getCtx().getBean("AverlineDAO");
		Date lastDate = DateUtil.getLastDealDate(date);
		List<Averline> averList = averlineDAO.findByProperty("dealdate", lastDate);
		
		int index = 0;
		
		while(averList.isEmpty()){
			lastDate = DateUtil.getLastDealDate(lastDate);
			averList = averlineDAO.findByProperty("dealdate", lastDate);
			index++;
			if(index>10){
				break;
			}
		}
		
		return averList;
	}
	
	public static void main(String[] args) throws SQLException {
		String s = "2014-05-";
		for (int i = 12; i < 13; i++) {
			if(i%7==3||i%7==4){
				continue;
			}
			Date date = DateUtil.parseDate(s+i);
			String dataStr = DateUtil.format(date);
			System.out.println(dataStr);
			new StockAnalyse(date);
		}
	}
}
